package genetics;

import java.util.Random;

/**
 * Bit mutation function.
 * @author pcdejager
 */
public class BitMutationFunction implements MutationFunction {
    /**
     * Constructor.
     * @param mutationRate The mutation rate to use
     */
    public BitMutationFunction(final double mutationRate) {
        rate = mutationRate;
    }

    /**
     * Mutate a bit gene.
     * @param random The random number generator to use
     * @param value The value to mutate
     * @param size The size of the gene
     * @return The resulting gene
     */
    public final int mutate(final Random random,
            final int value,
            final int size) {
        if (size != 1) {
            return -1;
        }
        if ((value < 0) || (value > 1)) {
            return -1;
        }
        if (random.nextDouble() < rate) {
            if (value == 1) {
                return 0;
            }
            return 1;
        }
        return value;
    }

    /**
     * The mutation rate to use.
     */
    private double rate = 0.0;
}
